package com.vpen.client.demo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.adapter.standard.StandardWebSocketSession;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;

import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;

/**
 *  客户端连接服务器的第二种方式
 *
 * @author 韦鹏
 * @date 2022/11/24 16:07
 */
@Slf4j
public class DemoClient {

    public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
        // 创建客户端
        StandardWebSocketClient client = new StandardWebSocketClient();


        // 连接
        ListenableFuture<WebSocketSession> future = client.doHandshake(new DemoWebSocketHandler(), "ws://localhost:8099/hello/weipeng");

        // 连接后的回调方法
        future.addCallback(new ListenableFutureCallback<WebSocketSession>() {
            @Override
            public void onFailure(Throwable ex) {
                log.error("连接出错:{}", ex.getMessage());
            }

            @Override
            public void onSuccess(WebSocketSession result) {
                try {
                    System.out.println("连接成功");
                    result.sendMessage(new TextMessage("你好，我已经连接成功了，准备推送消息吧"));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        // 获取连接的会话
        StandardWebSocketSession socketSession = (StandardWebSocketSession) future.get();

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            socketSession.sendMessage(new TextMessage(scanner.nextLine()));
        }
    }
}
